<?php

namespace App\Models;

use App\Http\Controllers\QrCodeController;
use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

/**
 * 文化配送座位表
 * Class ReservationModel
 * @package app\common\model
 */
class ReservationSeat extends BaseModel
{

    const CREATED_AT = 'create_time';
    const UPDATED_AT = null;

    public $table = 'reservation_seat';


    /**
     * 定义关联模型，一对多
     * 文化配送类型
     */
    public function reservationSeat()
    {
        return $this->hasMany(Reservation::class, 'reservation_id', 'id');
    }

    /**
     * 获取大于某个座位的座位id
     * @param   $reservation_id 预约id
     * @param   $number 座位号
     */
    public function getSeatId($reservation_id, $number)
    {
        return $this->where('reservation_id', $reservation_id)->where('number', '>', $number)->where('is_del', 1)->pluck('id');
    }

    /**
     * 座位预览 (获取所有的座位)  或判断座位是否存在
     * @param $reservation_id 预约id
     * @param $is_play 是否发布 1.发布 2.未发布    默认1   0 全部
     */
    public function seatList($reservation_id, $is_play = 0)
    {

        $res = $this->select('id', 'number', 'qr_url')
            ->where('is_del', 1)
            ->where(function ($query) use ($is_play) {
                if ($is_play) {
                    $query->where('is_play', $is_play);
                }
            })
            ->where('reservation_id', $reservation_id)
            ->get()
            ->toArray();
        return $res;
    }

    /**
     * 座位、格子预览
     * @param $reservation_id 预约id
     * @param $schedule_id 排版id
     * @param $schedule_type 排版类型
     * @param $make_time 预约时间
     * @param $is_play   是否发布 1.发布 2.未发布    默认1   0 全部
     */
    public function lists($reservation_id, $schedule_id, $schedule_type, $make_time, $is_play = 0, $limit = 10)
    {
        $res = $this->select('id', 'number', 'qr_code', 'qr_url', 'is_play')
            ->where('reservation_id', $reservation_id)
            ->where('is_del', 1)
            ->where(function ($query) use ($is_play) {
                if ($is_play) {
                    $query->where('is_play', $is_play);
                }
            })
            ->orderBy('id')
            ->paginate($limit)
            ->toArray();

        //判断此排版是否预约
        $reservation_info = Reservation::where('id', $reservation_id)->first();
        $reservationApplyObj = new ReservationApply();

        $max_seat_number = $this->maxSeatNumber($reservation_id);
        $end_seat = strlen($max_seat_number);
        foreach ($res['data'] as $key => $val) {
            $res['data'][$key]['number'] = $this->getSeatNumber($reservation_info->serial_prefix, $end_seat, $val['number']);
            // $makeStatus = $reservationApplyObj->makeStatus($reservation_id, $schedule_id, $schedule_type, $make_time, $reservation_info->kind, 1, $val['id'], [1, 3, 6], $reservation_info['node']);

            //新状态，获取预约状态
            $reservation_make_status = $reservationApplyObj->getMakeStatus($reservation_id, $schedule_id, $schedule_type, $make_time, $val['id'], [1, 3, 6], $reservation_info['node']);
            $res['data'][$key]['make_status'] = empty($reservation_make_status) ? 1 : ($reservation_make_status['status'] == 6 ? 3 : 2); //1 空闲  2 预约待领取  3 使用中
            $res['data'][$key]['is_make'] = empty($reservation_make_status) ? false : true; //false 未预约  true  已预约  以前状态，座位预约在用
        }
        return $res;
    }

    /**
     * 根据状态获取格子列表 (只能用于 node 为 7 的情况)
     * @param reservation_id  预约id
     * @param make_status   1 空闲  2 预约待领取  3 使用中
     */
    public function geSeatListBytStatus($reservation_id, $make_status = 1)
    {
        //判断此排版是否预约
        $reservation_info = Reservation::where('id', $reservation_id)->first();
        if ($reservation_info['node'] != 7) {
            return [];
        }

        $res = $this->where('reservation_id', $reservation_id)->where('is_del', 1)->where('is_play', 1)->get()->toArray();
        $reservationApplyObj = new ReservationApply();
        $max_seat_number = $this->maxSeatNumber($reservation_id);
        $end_seat = strlen($max_seat_number);
        $data = [];
        $i = 0;
        foreach ($res as $key => $val) {
            $number = $this->getSeatNumber($reservation_info->serial_prefix, $end_seat, $val['number']);
            //新状态，获取预约状态
            $reservation_make_status = $reservationApplyObj->getMakeStatus($reservation_id, null, null, null, $val['id'], [1, 3, 6], $reservation_info['node']);
            if ($make_status == 1 && empty($reservation_make_status)) {
                $data[$i]['number'] = $number;
                $data[$i]['id'] = $val['id'];
            }
            if ($make_status == 2 && ($reservation_make_status['status'] == 1 || $reservation_make_status['status'] == 3)) {
                $data[$i]['number'] = $number;
                $data[$i]['id'] = $val['id'];
            }
            if ($make_status == 3 && $reservation_make_status['status'] == 6) {
                $data[$i]['number'] = $number;
                $data[$i]['id'] = $val['id'];
            }
            $i ++;
        }
        return $data;
    }


    /**
     * 获取最大一个座位号
     * @param $reservation_id 预约id
     * @param $schedule_id 排版id
     * @param $make_time 预约时间
     * @param $is_play   是否发布 1.发布 2.未发布    默认1   0 全部
     */
    public function maxSeatNumber($reservation_id, $is_play = 0)
    {
        $max_seat_number = $this->where('reservation_id', $reservation_id)
            ->where('is_del', 1)
            ->where(function ($query) use ($is_play) {
                if ($is_play) {
                    $query->where('is_play', $is_play);
                }
            })
            ->max('number');
        return $max_seat_number;
    }


    /**
     * 修改座位
     * @param $reservation_id 预约id
     * @param $number 数量  新增数量 负数为删除
     * @param $have_number 已有数量  为0表示新增
     * @param $serial_prefix 编号前缀
     */
    public function change($reservation_id, $number = '', $have_number = '')
    {
        if (empty($number)) return 0;
        $surplus_number = $have_number + $number;
        $a = 0;

        if ($number < 0) {
            $this->where('reservation_id', $reservation_id)->where('number', '>', $surplus_number)->update(['is_del' => 2, 'change_time' => date('Y-m-d H:i:s')]);
        } elseif ($surplus_number > 0) {
            $data = [];
            $qrCodeObj = new QrCodeController();

            $have_number = $have_number + 1; //编号从1开始

            for ($i = $have_number; $i <= $surplus_number; $i++) {
                //查看之前是否有删除，有可以直接恢复
                $old_seat = $this->where('reservation_id', $reservation_id)->where('number', $i)->first();
                if ($old_seat) {
                    $old_seat->is_del = 1;
                    $old_seat->save();
                    continue;
                }

                $qr_code = $qrCodeObj->getQrCode('reservation_seat');
                if ($qr_code === false) {
                    throw new Exception("二维码生成失败,请重新添加");
                }

                $qr_url = $qrCodeObj->setQr($qr_code, true);
                $data[$a]['reservation_id'] = $reservation_id;
                $data[$a]['number'] = $i;
                $data[$a]['qr_code'] = $qr_code;
                $data[$a]['qr_url'] = $qr_url;
                $data[$a]['create_time'] = date('Y-m-d H:i:s');
                $a++;
            }
            if (!empty($data)) $this->insert($data);
        }
        return $number; //返回新增个数  0 表示不新增
    }


    /**
     * 获取座位编号
     * @param $serial_prefix 编号前缀
     * @param $strlen 位数
     * @param $number 编号
     */
    public function getSeatNumber($serial_prefix, $strlen, $number)
    {
        return $serial_prefix . sprintf("%0{$strlen}s", $number);
    }
}
